package service

import (
	"express/internal/dao"
	"express/internal/model"
	"express/pkg/app"
	"gorm.io/gorm"
)

type UserService struct {
}

func NewUserService() *UserService {
	return &UserService{}
}

func (u *UserService) CheckPhone(phone string) (bool, error) {
	_, err := dao.GetUserByPhone(phone)
	if err == gorm.ErrRecordNotFound {
		return true, nil
	}
	return false, err
}

func (u *UserService) AddUser(phone string, nickname string, passHash string, identifier int64) error {
	return dao.CreateUser(phone, nickname, passHash, identifier)
}

func (u *UserService) CheckPassByPhone(phone string, pass string) (bool, error) {
	user, _ := dao.GetUserByPhone(phone)
	if user == nil {
		return false, nil
	}
	ok := app.ValidatePasswords(user.Password, []byte(pass))
	return ok, nil
}

func (u *UserService) GetIdentifier(phone string) int64 {
	user, _ := dao.GetUserByPhone(phone)
	return user.Identifier
}

func (u *UserService) GetUserByPhone(phone string) *model.User {
	user, _ := dao.GetUserByPhone(phone)
	return user
}
